package com.itheima.health.security;

import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.*;

/**
 * @author ：seanyang
 * @date ：Created in 2019/6/14
 * @description ：授权验证业务类
 * @version: 1.0
 */

public class SecurityUserDetailsService implements UserDetailsService {

	// 模拟数据库的用户记录
	private static Map<String, User> userDb = new HashMap();

	@Autowired
	private BCryptPasswordEncoder encoder; // 引入加密对象
	static {
		User user1 = new User();
		user1.setUsername("admin");
		user1.setPassword("123");
		// 用户权限与角色
		Role role1 = new Role("系统管理员","ROLE_ADMIN");
		role1.getPermissions().add(new Permission("添加权限","add"));
		role1.getPermissions().add(new Permission("删除权限","delete"));
		role1.getPermissions().add(new Permission("更新权限","update"));
		role1.getPermissions().add(new Permission("查询权限","find"));
		user1.getRoles().add(role1);
		userDb.put(user1.getUsername(),user1);

		User user2 = new User();
		user2.setUsername("zhangsan");
		user2.setPassword("456");
		Role role2 = new Role("数据分析员","ROLE_DATA_READER");;
		role2.getPermissions().add(new Permission("查询权限","find"));
		user2.getRoles().add(role2);
		userDb.put(user2.getUsername(),user2);
	}
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 模拟从数据库读取用户信息
		User currUser = userDb.get(username);
		if (currUser == null){
			return  null;
		}
		String passwordInDb = currUser.getPassword();
		//String authPassword = "{noop}"+passwordInDb; // 默认加密规则，在密码前面是{noop}
		String authPassword = encoder.encode(passwordInDb);
		List<GrantedAuthority> authList = new ArrayList<>();
		for (Role role:currUser.getRoles()){
			// 角色关键词
			authList.add(new SimpleGrantedAuthority(role.getKeyword()));
			Set<Permission> permissions = role.getPermissions();
			// 权限关键词
			for(Permission p:permissions){
				authList.add(new SimpleGrantedAuthority(p.getKeyword()));
			}
		}
		// 构建UserDetails对象
		UserDetails userDetails = new org.springframework.security.core.userdetails.User(username,authPassword,authList);
		return userDetails;
	}
}
